package ewgenius.xube;

import java.io.FileNotFoundException;
import java.util.ArrayList;

import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;

import ewgenius.xube.engine.*;
import ewgenius.xube.engine.entities.Entity;
import ewgenius.xube.engine.graphics.*;
import ewgenius.xube.engine.graphics.gui.Gui;
import ewgenius.xube.engine.graphics.gui.GuiCollection;

public class XubeEngine {
	protected Settings settings = new Settings();
	protected Render render = new Render();
	protected InputState input;
	protected Timer timer = new Timer();
	
	protected ArrayList<Entity> entities = new ArrayList<Entity>();
	protected GuiCollection guis = new GuiCollection();

	public ArrayList<Entity> getEntities() {
		return entities;
	}
	
	public Render getRender() {
		return render;
	}
	
	public InputState getInputState() {
		return input;
	}
	
	public Timer getTimer() {
		return timer;
	}
	
	public void intialize() {
		try {
			settings.load();
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		}
		render.initialize(settings);
		try {
			input = new InputState();
		} catch (LWJGLException e) {
			e.printStackTrace();
		}
	}

	public void addEntity(Entity entity) {
		entities.add(entity);
	}
	
	public void addGuiElement(Gui gui) {
		guis.addInOrder(gui);
	}
	
	public static void traceConsole(Object message) {
		System.out.print(message);
		System.out.print('\n');
	}
	
	public void start() {
		mainLoop();
	}

	public void stop() {
		System.exit(0);
	}

	protected void mainLoop() {
		while (!Display.isCloseRequested()) {
			update();
			render();
		}
	}

	protected void update() {
		int time = timer.getDelta();
		input.update();
		
		for (Entity entity : entities ) {
			entity.update(time, this);
		}
		
		for(Gui gui : guis) {
			gui.update(time, this);
		}
		
		if (input.keyEsc) {
			stop();
		}
	}

	protected void destroy() {
		render.destroy();
	}

	protected void render() {
		render.begin();
		
		for (Entity entity : entities ) {
			entity.render(render);
		}
		
		//render.begin2DRender();
		
		for(Gui gui : guis) {
			gui.render(render);
		}
		
		//render.end2DRender();
		
		render.end();
	}
}